﻿using JmShared;
using JmShared.Models;
using SuperWebSocket.SubProtocol;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WebSocketServer.Filters;
using WebSocketServer.models;

namespace WebSocketServer.Commands
{
    [LoggedInValidationFilter(Order = 0)]
    [LogTimeCommandFilter(Order = 1)]
    public class SetGroupPrivilege : JsonSubCommand<JiveClientSession, MemberGroupPrivilege>
    {

        protected override void ExecuteJsonCommand(JiveClientSession session, MemberGroupPrivilege mgp)
        {
            var result = DB.DbManager.SetGroupPrivilege(session.ChatClient.MemberID, mgp.Username, mgp.GroupID, mgp.Privilege);
            SendJsonMessage(session, new DatabaseQueryResponse(result.Success, result.StatusText));

            List<ChatGroup> chatGroups = DB.DbManager.ReadChatGroups(session.ChatClient.Username);
            ChatGroup changedGroup =chatGroups.FirstOrDefault(x=>x.ID==mgp.GroupID.ToString());

            session.ChatClient.User.ChatGroups = chatGroups;

            foreach (Friend friend in session.ChatClient.FriendsList)
            {
                foreach (ChatClient cli in Clients.GetChatClientsFromUsername(friend.Username))
                {
                    ChatGroup grp = cli.User.ChatGroups.FirstOrDefault(x => x.ID == mgp.GroupID.ToString());
                    if (grp != null)
                    {
                        grp.GroupMembers = changedGroup.GroupMembers;
                    }
                }
            }

            session.ChatClient.BroadcastChatGroups(false, MessageReceipient.ContactsAndClient);
        }
    }
}
